﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Npgsql;
using System.Windows.Forms;

namespace Koala
{
    public class NodeTree : TreeNode
    {
        #region Attributes

        private string _Ip;
        private string _Port;
        private string _DB;
        private string _username;
        private string _pass;

        private NpgsqlConnection _conn;

        #endregion

        #region Contructors

        public NodeTree(string ip, string port, string db, string username, string pass) : base(ip + ":" + port)
        {
            _Ip = ip;
            _Port = port;
            _DB = db;
            _username = username;
            _pass = pass;

            _conn = new NpgsqlConnection();
        }

        #endregion

        #region Properties

        public NpgsqlConnection Connection
        {
            get { return _conn; }
        }

        public string UserName
        {
            get { return _username; }
        }

        public string Password
        {
            get { return _pass; }
        }

        #endregion

        private bool OpenConnection()
        {
            /*NpgsqlConnectionStringBuilder conn_str = new NpgsqlConnectionStringBuilder();

            conn_str.Database = _DB;
            conn_str.UserName = _username;
            conn_str.Host = _Ip;
            conn_str.Password =UTF8Encoding.Default.GetBytes(_pass);

            conn_str.Port = 5432;*/


            _conn.ConnectionString = "Server="+_Ip+
                                     ";Port="+_Port+
                                     ";User Id=" + _username +
                                     ";Password="+_pass+
                                     ";Database="+_DB+";";

            try
            {
                _conn.Open();

                if (_conn.State == System.Data.ConnectionState.Open)
                    return true;
                else
                    return false;
            }
            catch 
            {
                return false;
            }
        }

        private bool ClosenConnection()
        {
            try
            {
                if (_conn.State == System.Data.ConnectionState.Open)
                {
                    _conn.Close();
                    _conn.ClearPool();
                    _conn.Dispose();
                    _conn = null;
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool Connect()
        {
            return OpenConnection();
        }

        public bool Disconnect()
        {
            return ClosenConnection();
        }
    }
}
